<template>
    <div class="forget">
        <upNavbar :title="forgetParam" :bgColor="'#F5E9E9'"></upNavbar>
        <view class="back">
            <view class="logo">
                <image src="@/static/images/logo.png" alt="" />
                <view class="title">{{ $t('actionBindPhone') }}</view>
                <span class="text">{{ $t('CybersecurityLaw') }}</span>
            </view>
            <div class="phoneFrom">
                <up-form labelPosition="left" :model="model1" :rules="rules" ref="form1">
                    <up-form-item v-if="subsectionCurrent === 0" class="phoneNumber1" label="" prop="userInfo.number"
                        borderBottom ref="item1">
                        <u-input type="number" v-model="model1.userInfo.number" :placeholder="$t('Pleaseenternumber')"
                            style="flex: 1;"></u-input>
                    </up-form-item>
                    <up-form-item v-else class="phoneNumber1" label="" prop="userInfo.email" borderBottom ref="item1">
                        <u-input type="text" v-model="model1.userInfo.email" :placeholder="$t('Pleaseenteremail')"
                            style="flex: 1;"></u-input>
                    </up-form-item>
                    <up-form-item class="sendCode1" label="" prop="userInfo.sendCode" borderBottom ref="item1">
                        <u-input v-model="model1.userInfo.sendCode" :placeholder="$t('inputCaptcha')"
                            style="flex: 1;"></u-input>
                        <u-button style="width: 6rem;" :disabled="isDisabled" @click="handSendCode"
                            :loading="SendCodeLoading" :loadingText="''">{{
                                buttonText }}</u-button>
                    </up-form-item>
                </up-form>
                <div class="logBtn">
                    <u-button type="" :text="$t('binding')" @click="nextStep"></u-button>
                </div>
            </div>
        </view>
        <up-toast ref="uToastRef"></up-toast>
    </div>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app';
import { ref, reactive } from 'vue'
import { getPhoneCode, getEmailCode } from '@/api/login'
import { setPhone } from "@/api/setting/setting.js"
import upNavbar from '../../components/upNavbar.vue';
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const uToastRef = ref(null)
const subsectionList = ref([t('mobilephone'), t('email')])
const subsectionCurrent = ref(0)
const SendCodeLoading = ref(false)
const model1 = reactive({
    userInfo: {
        number: '',
        sendCode: '',
    },
    codeInfo: {
        number: '',
        possWord: '',
    },
})
const rules = {
    'userInfo.number': [
        {
            required: true,
            message: t('Mobilephonenumbercannotempty'),
            trigger: ['blur',]
        },
        {
            pattern: /^1[3-9]\d{9}$/,
            message: t('Themobilephonenumberincorrect'),
            trigger: ['blur',]
        }
    ],
    'userInfo.email': [
        {
            required: true,
            message: t('Mailboxcannotbeempty'),
            trigger: ['blur',]
        },
        {
            pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
            message: t('Incorrectmailboxformat'),
            trigger: ['blur',]
        }
    ],
    'userInfo.sendCode': {
        type: 'string',
        len: 6,
        required: true,
        message: t('inputCaptcha'),
        trigger: ['blur',]
    },
}
const isDisabled = ref(false)
const buttonText = ref(t('SendCaptcha'))
const forgetParam = ref('');
const countdown = ref(0);
const form1 = ref(null);
const nextStep = () => {// 绑定
    form1.value.validate().then((valid: any) => {
        if (valid) {
            setPhone({ phone: model1.userInfo.number, msg: model1.userInfo.sendCode }).then((res: any) => {
                if (res.code == 200) {
                    // 返回上一个页面
                    uni.navigateBack();
                } else {
                    uToastRef.value.show({
                        message: `${res.msg}`,
                        duration: 2000,
                        type: "default",
                        icon: "none",
                    })
                }
            }).catch((error: any) => {
                uToastRef.value.show({
                    message: `${error.msg}`,
                    duration: 2000,
                    type: "default",
                    icon: "none",
                })
            })
        } else { }
    })
}
// 获取验证码
const handSendCode = () => {
    if (isDisabled.value) return;
    let para = {
        phone: model1.userInfo.number
    }
    if (subsectionCurrent.value === 0) {
        para.phone = model1.userInfo.number
        const phoneReg = /^1[3-9]\d{9}$/
        if (!model1.userInfo.number) {
            uToastRef.value.show({
                message: t('Pleaseenternumber'),
                duration: 2000,
                type: "default",
                icon: "none",
            })
            return
        }
        if (!phoneReg.test(model1.userInfo.number)) {
            uToastRef.value.show({
                message: t('Pleaseentercorrectemailnumber'),
                duration: 2000,
                type: "default",
                icon: "none",
            })
            return
        }
        SendCodeLoading.value = true
        getPhoneCode({ phone: model1.userInfo.number }).then(res => {
            if (res.code === 200) {
                isDisabled.value = true;
                buttonText.value = '60s';
                countdown.value = 60;
                uToastRef.value.show({
                    message: t('haveSendCode'),
                    duration: 2000,
                    type: "default",
                    icon: "none",
                })
            } else {
                uToastRef.value.show({
                    message: `${res.msg}`,
                    duration: 2000,
                    type: "default",
                    icon: "none",
                })
            }
        }).catch(err => {
            uToastRef.value.show({
                message: `${err.msg}`,
                duration: 2000,
                type: "default",
                icon: "none",
            })
        }).finally(() => {
            SendCodeLoading.value = false
            const intervalId = setInterval(() => {
                if (countdown.value <= 0) {
                    clearInterval(intervalId); // 清除定时器
                    isDisabled.value = false;
                    buttonText.value = t('SendCaptcha');
                } else {
                    countdown.value -= 1;
                    buttonText.value = `${countdown.value}s`;
                }
            }, 1000);
        })
    } else if (subsectionCurrent.value === 1) {
        para.phone = model1.userInfo.email
        const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
        if (!model1.userInfo.email) {
            uToastRef.value.show({
                message: t('bindEmailPlaseholder'),
                duration: 2000,
                type: "default",
                icon: "none",
            })
            return
        }
        if (!emailReg.test(model1.userInfo.email)) {
            uToastRef.value.show({
                message: t('Pleaseentercorrectemailaddress'),
                duration: 2000,
                type: "default",
                icon: "none",
            })
            return;
        }
        SendCodeLoading.value = true
        getEmailCode(model1.userInfo.email).then(res => {
            if (res.code === 200) {
                isDisabled.value = true;
                buttonText.value = '60s';
                countdown.value = 60;
                uToastRef.value.show({
                    message: t('haveSendCode'),
                    duration: 2000,
                    type: "default",
                    icon: "none",
                })
            } else {
                uToastRef.value.show({
                    message: `${res.msg}`,
                    duration: 2000,
                    type: "default",
                    icon: "none",
                })
            }
        }).catch((err: any) => {
            uToastRef.value.show({
                message: `${err.msg}`,
                duration: 2000,
                type: "default",
                icon: "none",
            })
        }).finally(() => {
            SendCodeLoading.value = false
            const intervalId = setInterval(() => {
                if (countdown.value <= 0) {
                    clearInterval(intervalId); // 清除定时器
                    isDisabled.value = false;
                    buttonText.value = t('SendCaptcha');
                } else {
                    countdown.value -= 1;
                    buttonText.value = `${countdown.value}s`;
                }
            }, 1000);
        })
    }
}
onLoad((options) => {
    // 从 options 中获取参数
    forgetParam.value = options.forget;
});
const sectionChange = (index: number) => {
    subsectionCurrent.value = index;
}
</script>
<style scoped lang="scss">
.forget {
    width: 100%;
    height: 100%;
    background: linear-gradient(180deg, #F4E6E6, #ffffff);

    .back {
        width: 100%;
        position: fixed;
        top: 280rpx;

        .logo {
            text-align: center;
            margin-bottom: 10rpx;

            image {
                width: 240rpx;
                height: 240rpx;
            }

            .title {
                font-size: 30rpx;
                font-weight: bold;
            }

            .text {
                width: 83%;
                font-size: 22rpx;
                font-weight: bold;
                display: inline-block;
                margin-top: 30rpx;
                text-align: left;
            }
        }

        .up {
            width: 50%;
            margin: 0 auto;
        }

        .phoneFrom {
            width: 85%;
            margin: 0 auto;

            .phoneNumber1 {
                .u-input {
                    background-color: #F2F2F2;
                }

                .u-input--radius {
                    border-radius: 15px;
                }
            }

            .sendCode1 {
                .u-input {
                    background-color: #F2F2F2;
                }

                .u-input--radius {
                    border-radius: 15px 0 0 15px;
                }

                .u-button {
                    border-radius: 0 15px 15px 0;
                }
            }

            .logBtn {
                margin: 0 auto;
                margin-top: 28rpx;
                width: 100%;
                text-align: center;

                .u-button {
                    color: #fff;
                    height: 80rpx;
                    font-weight: 600;
                    border-radius: 10px;
                    background-color: #de868f;
                    border: 1px solid #bbbbbb;
                }

            }
        }
    }
}
</style>